import React, { useState, useCallback, useRef, useEffect } from 'react';
import { X, Upload, Book, FileText, Trash2, Eye, Search, ArrowLeft, Calendar, FileIcon, Database, CheckCircle, AlertCircle, Loader2, RefreshCw, ExternalLink } from 'lucide-react';
import { Message, KnowledgeFile } from '../types';
import { FloatingChat } from './FloatingChat';
import { ChatMessage } from './ChatMessage';
import { ChatInput } from './ChatInput';

interface KnowledgeBaseProps {
  onClose: () => void;
  files: KnowledgeFile[];
  onFileUpload: (file: File) => Promise<void>;
  onFileDelete: (fileId: string) => void;
  onFilePreview: (fileId: string) => void;
  onAskQuestion: (question: string) => Promise<Message>;
  onEmbedFile: (fileId: string) => Promise<void>;
  onEmbedAllFiles: () => Promise<void>;
  onLoadChatHistory: (sessionId?: string) => Promise<Message[]>;
}

export function KnowledgeBase({
  onClose,
  files,
  onFileUpload,
  onFileDelete,
  onFilePreview,
  onAskQuestion,
  onEmbedFile,
  onEmbedAllFiles,
  onLoadChatHistory
}: KnowledgeBaseProps) {
  const [isDragging, setIsDragging] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const [showUploadArea, setShowUploadArea] = useState(false);
  const [question, setQuestion] = useState('');
  const [showChat, setShowChat] = useState(false);
  const [chatExpanded, setChatExpanded] = useState(false);
  const [chatMessages, setChatMessages] = useState<Message[]>([]);
  const [isTyping, setIsTyping] = useState(false);
  const [isEmbeddingAll, setIsEmbeddingAll] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [uploadError, setUploadError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<'files' | 'chat'>('files');
  const [currentSessionId, setCurrentSessionId] = useState<string | undefined>(undefined);
  
  // 引用底部输入框容器
  const inputContainerRef = useRef<HTMLDivElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const chatContainerRef = useRef<HTMLDivElement>(null);

  // 检查是否有需要嵌入的文档
  const hasFilesToEmbed = files.some(file => 
    file.embeddingStatus !== 'completed' && file.embeddingStatus !== 'processing'
  );

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
  }, []);

  const handleDrop = useCallback(async (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    
    const files = Array.from(e.dataTransfer.files);
    const validFiles = files.filter(file => 
      ['text/plain', 'application/pdf', 'application/msword', 
       'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
      .includes(file.type)
    );

    if (validFiles.length > 0) {
      setIsUploading(true);
      try {
        await Promise.all(validFiles.map(file => onFileUpload(file)));
      } finally {
        setIsUploading(false);
        setShowUploadArea(false);
      }
    }
  }, [onFileUpload]);

  const handleFileInput = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    if (files.length > 0) {
      setIsUploading(true);
      try {
        await Promise.all(files.map(file => onFileUpload(file)));
      } finally {
        setIsUploading(false);
        setShowUploadArea(false);
      }
    }
  }, [onFileUpload]);

  const formatFileSize = (bytes: number) => {
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
    return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
  };

  const handleAskQuestion = async (question: string) => {
    // 添加用户消息
    const userMessage: Message = {
      id: `user-${Date.now()}`,
      content: question,
      sender: 'user',
      timestamp: new Date(),
      status: 'sent'
    };
    
    setChatMessages(prev => [...prev, userMessage]);
    setIsTyping(true);
    
    try {
      // 调用知识库问答 API
      const aiMessage = await onAskQuestion(question);
      
      // 如果返回了会话 ID，保存它
      if (aiMessage.sessionId) {
        setCurrentSessionId(String(aiMessage.sessionId));
      }
      
      // 添加 AI 回复消息
      setChatMessages(prev => [...prev, aiMessage]);
    } catch (error) {
      console.error('知识库问答失败:', error);
      
      // 添加错误消息
      const errorMessage: Message = {
        id: `error-${Date.now()}`,
        content: '抱歉，我无法回答这个问题。',
        sender: 'ai',
        timestamp: new Date(),
        status: 'failed',
        errorMessage: error instanceof Error ? error.message : '知识库问答失败'
      };
      
      setChatMessages(prev => [...prev, errorMessage]);
    } finally {
      setIsTyping(false);
    }
  };

  // 处理输入框获取焦点
  const handleInputFocus = () => {
    setShowChat(true);
  };

  // 获取文件图标
  const getFileIcon = (fileType: string) => {
    if (fileType.includes('pdf')) {
      return <FileIcon className="w-full h-full text-red-500" />;
    } else if (fileType.includes('doc')) {
      return <FileIcon className="w-full h-full text-blue-500" />;
    } else if (fileType.includes('txt')) {
      return <FileText className="w-full h-full text-gray-500" />;
    } else {
      return <FileText className="w-full h-full text-blue-500" />;
    }
  };

  // 获取嵌入状态图标和颜色
  const getEmbeddingStatusInfo = (status?: string) => {
    switch (status) {
      case 'completed':
        return { 
          icon: <CheckCircle className="w-4 h-4 text-green-500" />, 
          text: '已嵌入',
          textColor: 'text-green-600'
        };
      case 'processing':
        return { 
          icon: <Loader2 className="w-4 h-4 text-blue-500 animate-spin" />, 
          text: '处理中',
          textColor: 'text-blue-600'
        };
      case 'failed':
        return { 
          icon: <AlertCircle className="w-4 h-4 text-red-500" />, 
          text: '嵌入失败',
          textColor: 'text-red-600'
        };
      default:
        return { 
          icon: <Database className="w-4 h-4 text-gray-400" />, 
          text: '未嵌入',
          textColor: 'text-gray-500'
        };
    }
  };

  // 处理嵌入文件
  const handleEmbedFile = async (fileId: string) => {
    try {
      await onEmbedFile(fileId);
    } catch (error) {
      console.error('嵌入文件失败:', error);
      // 可以添加错误提示
    }
  };

  // 格式化日期
  const formatDate = (date: Date) => {
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'numeric',
      day: 'numeric'
    });
  };

  // 处理一键嵌入所有文档
  const handleEmbedAllFiles = async () => {
    if (isEmbeddingAll) return;
    
    setIsEmbeddingAll(true);
    try {
      await onEmbedAllFiles();
    } catch (error) {
      console.error('嵌入所有文件失败:', error);
      // 可以添加错误提示
    } finally {
      setIsEmbeddingAll(false);
    }
  };

  // 滚动到底部
  const scrollToBottom = () => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
    }
  };

  // 监听消息变化，自动滚动到底部
  useEffect(() => {
    scrollToBottom();
  }, [chatMessages]);

  // 处理键盘事件
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      if (question.trim()) {
        handleAskQuestion(question.trim());
        setQuestion(''); // 清空输入框
      }
    }
  };

  // 处理提问按钮点击
  const handleQuestionSubmit = () => {
    if (question.trim()) {
      handleAskQuestion(question.trim());
      setQuestion(''); // 清空输入框
    }
  };

  // 加载会话历史
  const loadChatHistory = async () => {
    try {
      setIsTyping(true);
      const messages = await onLoadChatHistory(currentSessionId);
      setChatMessages(messages);
    } catch (error) {
      console.error('加载知识库会话历史失败:', error);
    } finally {
      setIsTyping(false);
    }
  };

  // 在组件挂载和会话 ID 变化时加载历史
  useEffect(() => {
    if (showChat) {
      loadChatHistory();
    }
  }, [showChat, currentSessionId]);

  return (
    <div className="fixed inset-0 bg-gray-50 flex flex-col z-50">
      {/* 头部 */}
      <div className="bg-white border-b px-6 py-4 flex items-center justify-between">
        <div className="flex items-center gap-3">
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-full transition-colors"
          >
            <ArrowLeft className="w-5 h-5 text-gray-600" />
          </button>
          <div className="flex items-center gap-2">
            <Book className="w-6 h-6 text-blue-600" />
            <h1 className="text-xl font-semibold text-gray-800">知识库</h1>
          </div>
        </div>
        
        <div className="flex items-center gap-2">
          {/* 一键嵌入所有文档按钮 */}
          {files.length > 0 && (
            <button
              onClick={handleEmbedAllFiles}
              disabled={isEmbeddingAll || !hasFilesToEmbed}
              className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${
                hasFilesToEmbed 
                  ? 'bg-green-600 text-white hover:bg-green-700' 
                  : 'bg-gray-200 text-gray-500 cursor-not-allowed'
              }`}
              title={hasFilesToEmbed ? "嵌入所有未处理的文档" : "所有文档已嵌入"}
            >
              {isEmbeddingAll ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  <span>处理中...</span>
                </>
              ) : (
                <>
                  <RefreshCw className="w-5 h-5" />
                  <span>一键嵌入</span>
                </>
              )}
            </button>
          )}
          
          <button
            onClick={() => setShowUploadArea(true)}
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            <Upload className="w-5 h-5" />
            <span>上传文档</span>
          </button>
        </div>
      </div>

      {/* 主体内容 */}
      <div className="flex-1 overflow-auto p-6">
        {/* 上传区域 - 仅在点击上传按钮后显示 */}
        {showUploadArea && (
          <div
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
            onDrop={handleDrop}
            className={`p-8 border-2 border-dashed m-4 rounded-lg text-center transition-colors ${
              isDragging ? 'border-blue-500 bg-blue-50' : 'border-gray-300'
            }`}
          >
            <Upload className="w-8 h-8 text-blue-600 mx-auto mb-2" />
            <p className="text-gray-600 mb-2">
              拖拽文件到此处，或点击选择文件
            </p>
            <p className="text-sm text-gray-500 mb-4">
              支持格式：TXT, PDF, DOC, DOCX
            </p>
            <div className="flex justify-center gap-4">
              <label className="inline-block">
                <input
                  ref={fileInputRef}
                  type="file"
                  className="hidden"
                  accept=".txt,.pdf,.doc,.docx"
                  multiple
                  onChange={handleFileInput}
                />
                <span className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 cursor-pointer transition-colors">
                  选择文件
                </span>
              </label>
              <button
                onClick={() => setShowUploadArea(false)}
                className="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors"
              >
                取消
              </button>
            </div>
            
            {isUploading && (
              <div className="mt-4 text-blue-600">
                <p>正在上传文件，请稍候...</p>
              </div>
            )}
          </div>
        )}

        {/* 文件列表 */}
        <div className="bg-white rounded-lg shadow-sm overflow-hidden">
          <div className="px-6 py-4 border-b flex justify-between items-center">
            <h2 className="text-lg font-medium text-gray-800">我的知识库文档</h2>
            
            {/* 嵌入状态统计 */}
            {files.length > 0 && (
              <div className="flex items-center gap-3 text-sm">
                <div className="flex items-center gap-1 text-green-600">
                  <CheckCircle className="w-4 h-4" />
                  <span>{files.filter(f => f.embeddingStatus === 'completed').length} 已嵌入</span>
                </div>
                {files.some(f => f.embeddingStatus === 'processing') && (
                  <div className="flex items-center gap-1 text-blue-600">
                    <Loader2 className="w-4 h-4 animate-spin" />
                    <span>{files.filter(f => f.embeddingStatus === 'processing').length} 处理中</span>
                  </div>
                )}
                {files.some(f => f.embeddingStatus === 'pending' || f.embeddingStatus === 'failed') && (
                  <div className="flex items-center gap-1 text-gray-500">
                    <Database className="w-4 h-4" />
                    <span>{files.filter(f => f.embeddingStatus === 'pending' || f.embeddingStatus === 'failed').length} 待处理</span>
                  </div>
                )}
              </div>
            )}
          </div>
          
          {files.length === 0 ? (
            <div className="p-8 text-center">
              <Book className="w-12 h-12 mx-auto text-gray-300 mb-3" />
              <p className="text-gray-500 mb-1">您的知识库还没有文档</p>
              <p className="text-sm text-gray-400 mb-4">上传文档后，AI 将能够基于这些内容回答问题</p>
              <button
                onClick={() => setShowUploadArea(true)}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
              >
                上传第一个文档
              </button>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 p-4">
              {files.map(file => {
                const statusInfo = getEmbeddingStatusInfo(file.embeddingStatus);
                
                return (
                  <div key={file.id} className="border rounded-lg overflow-hidden hover:shadow-md transition-shadow">
                    <div className="p-4 flex items-start gap-3">
                      <div className="w-10 h-10 flex-shrink-0 bg-gray-100 rounded-lg flex items-center justify-center">
                        {getFileIcon(file.type)}
                      </div>
                      <div className="flex-1 min-w-0">
                        <h3 className="font-medium text-gray-800 truncate" title={file.name}>
                          {file.name}
                        </h3>
                        <div className="flex items-center gap-2 text-xs text-gray-500 mt-1">
                          <span>{formatFileSize(file.size)}</span>
                          <span>•</span>
                          <div className="flex items-center">
                            <Calendar className="w-3 h-3 mr-1" />
                            <span>{formatDate(file.uploadedAt)}</span>
                          </div>
                          
                          {/* 嵌入状态 */}
                          <div className={`flex items-center gap-1 text-xs ${statusInfo.textColor} mt-2`}>
                            {statusInfo.icon}
                            <span>{statusInfo.text}</span>
                            {file.lastEmbeddedAt && (
                              <>
                                <span className="text-gray-400 mx-1">•</span>
                                <span className="text-gray-500">
                                  {formatDate(file.lastEmbeddedAt)}
                                </span>
                              </>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                    
                    <div className="bg-gray-50 px-4 py-2 flex justify-end gap-2 border-t">
                      {/* 嵌入按钮 */}
                      {file.embeddingStatus !== 'processing' && (
                        <button
                          onClick={() => handleEmbedFile(file.id)}
                          disabled={file.embeddingStatus === 'processing'}
                          className={`p-1.5 rounded transition-colors ${
                            file.embeddingStatus === 'completed' 
                              ? 'text-gray-400 hover:text-blue-600 hover:bg-blue-50' 
                              : 'text-blue-600 hover:bg-blue-50'
                          }`}
                          title={file.embeddingStatus === 'completed' ? '重新嵌入' : '嵌入文档'}
                        >
                          <Database className="w-4 h-4" />
                        </button>
                      )}
                      
                      <button
                        onClick={() => onFilePreview(file.id)}
                        className="p-1.5 text-gray-500 hover:text-blue-600 hover:bg-blue-50 rounded transition-colors"
                        title="预览"
                      >
                        <Eye className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => onFileDelete(file.id)}
                        className="p-1.5 text-gray-500 hover:text-red-600 hover:bg-red-50 rounded transition-colors"
                        title="删除"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>

      {/* 底部提问区域 */}
      <div className="bg-white border-t p-4 relative" ref={inputContainerRef}>
        <div className="max-w-3xl mx-auto">
          <p className="text-sm text-gray-500 mb-2">基于知识库提问</p>
          <div className="flex gap-2">
            <div className="flex-1 relative">
              <textarea
                value={question}
                onChange={(e) => setQuestion(e.target.value)}
                onKeyDown={handleKeyDown}
                onFocus={handleInputFocus}
                placeholder="输入您的问题，AI 将基于知识库内容回答..."
                className="w-full resize-none rounded-lg border border-gray-200 p-3 pr-10 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                rows={1}
              />
              <Search className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
            </div>
            <button
              onClick={handleQuestionSubmit}
              disabled={!question.trim()}
              className="px-4 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              提问
            </button>
          </div>
        </div>

        {/* 浮动聊天窗口 - 直接在输入框上方显示 */}
        {showChat && (
          <div className="absolute bottom-full left-0 right-0 mb-4 px-4">
            <div className="max-w-3xl mx-auto">
              <FloatingChat
                onClose={() => setShowChat(false)}
                messages={chatMessages}
                isTyping={isTyping}
                expanded={chatExpanded}
                onToggleExpand={() => setChatExpanded(!chatExpanded)}
              />
            </div>
          </div>
        )}
      </div>
    </div>
  );
}